package com.vf.cloud.paas.app.master.api.itester.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.paas.app.master.api.itester.service.IITester;
import com.vf.cloud.paas.app.master.common.domain.ApiTest;
import com.vf.cloud.paas.common.util.UuidUtil;

@Service
public class ITesterImpl implements IITester {

	public List<ApiTest> list(ApiTest param) {
		String _sql = "select * from " + ApiTest.TABLE_NAME + " where pid=? order by sort asc ";
		List<ApiTest> users = ApiTest.dao.find(_sql, param.getId());
		for (ApiTest u : users) {
			param.setId(u.getId());
			u.setChildren(getChildrens(param));
		}
		return users;
	}

	public List<ApiTest> getChildrens(ApiTest param) {
		String _sql = "select * from " + ApiTest.TABLE_NAME + " where pid=?  order by sort asc ";
		List<ApiTest> users = ApiTest.dao.find(_sql, param.getId());
		for (ApiTest u : users) {
			param.setId(u.getId());
			u.setChildren(getChildrens(param));
		}
		return users;
	}

	@Override
	public void delete(String id) {
		deleteChildrens(id);
	}

	public void deleteChildrens(String id) {
		List<ApiTest> apiTests = ApiTest.dao.find("select id from " + ApiTest.TABLE_NAME + " where pid=? ", id);
		for (ApiTest apiTest : apiTests) {
			if (apiTest.delete()) {
				deleteChildrens(apiTest.getId());
			}
		}
	}

	@Override
	public ApiTest copy(String id) {
		ApiTest apiTest = ApiTest.dao.findById(id);
		double version = Db.queryDouble("SELECT MAX(version) as version from api_test where type='version' ");
		if (apiTest != null) {
			apiTest.setId(UuidUtil.getUUID());
			apiTest.setVersion(version + 0.01);
			if (apiTest.save()) {
				copyChildrens(id, apiTest);
			}
		}
		return apiTest;
	}

	public void copyChildrens(String id, ApiTest api) {
		List<ApiTest> apiTests = ApiTest.dao.find("select * from " + ApiTest.TABLE_NAME + " where pid=? ", id);
		for (ApiTest apiTest : apiTests) {
			String oldId = apiTest.getId();
			apiTest.setId(UuidUtil.getUUID());
			apiTest.setPid(api.getId());
			if (apiTest.save()) {
				copyChildrens(oldId, apiTest);
			}
		}
	}

	@Override
	public List<ApiTest> listByVersion(ApiTest param) {
		ApiTest apiTest=ApiTest.dao.findFirst("select * from " + ApiTest.TABLE_NAME + " where version=? and type='version' order by sort asc ", param.getVersion());
		if(apiTest!=null) {
			String _sql = "select * from " + ApiTest.TABLE_NAME + " where pid=? order by sort asc ";
			List<ApiTest> users = ApiTest.dao.find(_sql, apiTest.getId());
			for (ApiTest u : users) {
				param.setId(u.getId());
				u.setChildren(getChildrens(param));
			}
			return users;
		}
		return null;
	}

}
